import _ from 'lodash';
import { ipcMain, Event, BrowserWindow, app, globalShortcut, Accelerator, webContents } from 'electron';
import IElectronModule from './bg_base';


export const REGISTER_KEY = "shortcut-register";
export const REGISTER_KEY_RET = "shortcut-register-ret";

class Shortcut implements IElectronModule {

    private win?: BrowserWindow;
    private _mapKeys: Map<Accelerator, Set<{ sender: webContents, channel: string }>> = new Map<Accelerator, Set<{ sender: webContents, channel: string }>>();

    install(win: Electron.BrowserWindow): void {

        ipcMain.on(REGISTER_KEY, this.registerKey.bind(this));

    }

    private registerKey(event: Event, { key, channel }: { key?: string, channel?: string } = {}) {
        let { sender } = event;

        if (key && channel && key.length > 0 && channel.length > 0) {
            if (this._mapKeys.has(key)) {
                let r = this._mapKeys.get(key);
                if (r) {
                    r.add({ sender, channel });
                }
            }
            else {
                let r = new Set<{ sender: webContents, channel: string }>();
                r.add({ sender, channel });
                this._mapKeys.set(key, r)
                globalShortcut.register(key, () => {
                    let r = this._mapKeys.get(key);
                    if (r) {
                        r.forEach(({ sender, channel }) => sender.send(channel));
                    }
                });

            }
            sender.send(REGISTER_KEY_RET, {
                status: "success",
                message: "注册成功。"
            })
        } else {
            sender.send(REGISTER_KEY_RET, {
                status: "error",
                message: "请输入正确的参数。"
            });

        }



    }

}

export default new Shortcut();